package com.lizhi.note.config;

import com.lizhi.note.exception.TokenInvalidException;
import com.lizhi.note.service.TokenBlackListCacheService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private TokenBlackListCacheService tokenBlackListCacheService;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    private final List<String> allowedPaths = new ArrayList<>(); // 需要校验的路径

    public JwtAuthFilter() {
        this.allowedPaths.add("/api/auth/login");
        this.allowedPaths.add("/error");
        this.allowedPaths.add("/api/auth/public-key");
        this.allowedPaths.add("/exception/throw");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String jwt;
        final String username;

        String path = request.getRequestURI();
        if (isPathAllowed(path)) {
            filterChain.doFilter(request, response);
            return;
        }

        jwt = extractCookie(request);
        if (tokenBlackListCacheService.containsKey(jwt)) {
            throw new TokenInvalidException("token失效");
        }
        try{
            username = jwtUtils.extractUsername(jwt);
        }catch (IllegalArgumentException e){
            throw new TokenInvalidException(e.getMessage());
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (jwtUtils.validateToken(jwt, userDetails)) {
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails,
                        jwt,
                        userDetails.getAuthorities()
                );

                authToken.setDetails(
                        new WebAuthenticationDetailsSource().buildDetails(request)
                );

                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }

        filterChain.doFilter(request, response);
    }

    public String extractCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return "";
    }

    private boolean isPathAllowed(String path) {
        for (String allowedPath : allowedPaths) {
            if (pathMatcher.match(allowedPath, path)) {
                return true;
            }
        }
        return false;
    }

}
